package com.ktjiaoyu.ktmall.dao.impl;

import com.ktjiaoyu.ktmall.dao.BaseDao;
import com.ktjiaoyu.ktmall.dao.ProductDao;
import com.ktjiaoyu.ktmall.entity.Product;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductDaoImpl extends BaseDao implements ProductDao {
    @Override
    public int delete(Long id) {
        String sql = "update kt_product set is_deleted=1 ,update_time=now() where id=?";
        try {
            return executeUpdate(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
        }
    }

    @Override
    public int updateStatus(Long id, Integer status) {
        String sql = "update kt_product set status=?,update_time=now() where id=?";
        try {
            return executeUpdate(sql,status,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
        }
    }

    @Override
    public Product findById(Long id) {
        String sql = "select * from kt_product where id = ? and is_deleted = 0";
        try {
            List<Product> list = executeQuery(sql,resultSet -> {
                List<Product> I = new ArrayList<>();
                try {
                    while (resultSet.next()){
                        I.add(extractProduct(resultSet));
                    }
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                } finally {
                }
                return I;
            },id);
            return list.isEmpty() ? null : list.get(0);
        } catch (SQLException e) {
            return null;
        } finally {
        }

    }

    @Override
    public int insert(Product pro) {
        String sql = "INSERT INTO `ktdb`.`kt_product`(" +
                "`title`, `subtitle`, `category_id`, `category_path`, " +
                "`brand`, `main_image`, `images`, " +
                "`description`, `price`, `original_price`, " +  // 去掉多余的逗号
                "`stock`, `status`, `is_deleted`, `create_time`, `update_time`" +  // 正确闭合列名列表
                ") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,default,now(),now())";  // 只保留一个右括号

        try {
            return executeUpdate(sql,pro.getTitle(),pro.getSubtitle(),pro.getCategory_id(),
                    pro.getCategory_path(),pro.getBrand(),pro.getMain_image(),
                    pro.getImages(),pro.getDescription(),pro.getPrice(),pro.getOriginal_price()
            ,pro.getStock(),pro.getStatus());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
        }
    }

    @Override
    public int update(Product product) {
        StringBuilder sql = new StringBuilder( "UPDATE `ktdb`.`kt_product` SET ");
        List<Object> params = new ArrayList<>();
        if (product.getTitle() != null){
            sql.append("`title` = ? ,");
            params.add(product.getTitle());

        }
        if (product.getSubtitle() != null){
            sql.append( "`subtitle` = ? ,");
            params.add(product.getSubtitle());
        }
        if (product.getCategory_id() != null){
            sql.append("`category_id` = ? ,");
            params.add(product.getCategory_id());
        }
        if (product.getCategory_path() != null){
            sql.append("`category_path` = ? ,");
            params.add(product.getCategory_path());

        }
        if (product.getBrand() != null){
            sql.append("`brand` = ? ,");
            params.add(product.getBrand());
        }
        if (product.getMain_image() != null){
            sql.append("`main_image` = ? ,");
            params.add(product.getMain_image());
        }
        if (product.getImages() != null){
            sql.append( "`images` = ? ,");
            params.add(product.getImages());
        }
        if (product.getDescription() != null){
            sql.append("`description` = ? ,");
            params.add(product.getDescription());
        }
        if (product.getPrice() != null){
            sql.append( "`price` = ? ,");
            params.add(product.getPrice());
        }
        if (product.getOriginal_price() != null){
            sql.append("`original_price` = ? ,");
            params.add(product.getOriginal_price());
        }
        if (product.getStock() != null){
            sql.append( "`stock` = ? ,");
            params.add(product.getStock());
        }
        if (product.getSales() != null){
            sql.append( "`sales` = ? ,");
            params.add(product.getSales());
        }
        if (product.getStatus() != null){
            sql.append( "`status` = ? ,");
            params.add(product.getStatus());
        }
        if (product.getIs_deleted() != null){
            sql.append("`is_deleted` = ? ,");
            params.add(product.getIs_deleted());

        }
//        if (product.getCreate_time() != null){
//            sql += "`create_time` = ? ,";
//            params.add(product.getCreate_time());
//        }
            sql.append("`update_time` = now()  where id = ? ");
        params.add(product.getId());

        try {
            return executeUpdate(sql.toString(),params.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        } finally {
        }
    }

    // 分页查询：修复 SQL 拼接和逻辑判断错误
    @Override
    public List<Product> findList(String title, Long categoryId, int page, int pageSize) {
        StringBuilder sql = new StringBuilder("select * from `kt_product` where is_deleted = 0 ");
        List<Object> params = new ArrayList<Object>();

        if (title != null && !title.isEmpty()) {
            sql.append(" and title like ? ");
            params.add("%" + title + "%"); // 参数值带 %，匹配模糊查询
        }

        // 修复3：补充 categoryId 条件（原代码漏了，否则无法按分类筛选，可选但建议加上）
        if (categoryId != null) {
            sql.append(" and find_in_set(?, category_path) "); // 复用 count 方法的分类筛选逻辑
            params.add(categoryId);
        }

        // 分页条件：limit 后面的两个 ? 对应 page 和 pageSize，参数数量匹配
        sql.append(" order by create_time desc limit ?, ? ");
        params.add((page - 1) * pageSize); // 起始索引（第 N 页的起始位置）
        params.add(pageSize); // 每页条数

        try {
            return executeQuery(sql.toString(), resultSet -> {
                List<Product> list = new ArrayList<>();
                try {
                    while (resultSet.next()) {
                        list.add(extractProduct(resultSet));
                    }
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                return list;
            }, params.toArray());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    // 总数查询：逻辑正确，但建议统一代码风格
    @Override
    public int count(String title, Long categoryId) {
        StringBuilder sql = new StringBuilder("select count(*) from `kt_product` where is_deleted = 0 ");
        List<Object> params = new ArrayList<>();

        // 同样修复 title 的逻辑判断（原代码此处也有相同错误！）
        if (title != null && !title.isEmpty()) {
            sql.append(" and title like ? ");
            params.add("%" + title + "%");
        }

        if (categoryId != null) {
            sql.append(" and find_in_set(?, category_path) ");
            params.add(categoryId);
        }

        try {
            List<Integer> result = executeQuery(sql.toString(), resultSet -> {
                List<Integer> countList = new ArrayList<>();
                try {
                    if (resultSet.next()) {
                        countList.add(resultSet.getInt(1)); // 获取 count(*) 结果
                    }
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                return countList;
            }, params.toArray());
            return result.isEmpty() ? 0 : result.get(0);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    // 提取 Product 数据：逻辑正确，无需修改
    private Product extractProduct(ResultSet resultSet) throws SQLException {
        Product product = new Product();
        product.setId(resultSet.getLong("id"));
        product.setTitle(resultSet.getString("title"));
        product.setSubtitle(resultSet.getString("subtitle"));
        product.setCategory_id(resultSet.getLong("category_id"));
        product.setCategory_path(resultSet.getString("category_path"));
        product.setBrand(resultSet.getString("brand"));
        product.setMain_image(resultSet.getString("main_image"));
        product.setImages(resultSet.getString("images"));
        product.setDescription(resultSet.getString("description"));
        product.setPrice(resultSet.getDouble("price"));
        product.setOriginal_price(resultSet.getDouble("original_price"));
        product.setStock(resultSet.getInt("stock"));
        product.setSales(resultSet.getInt("sales"));
        product.setStatus(resultSet.getInt("status"));
        product.setIs_deleted(resultSet.getInt("is_deleted"));
        product.setCreate_time(resultSet.getString("create_time"));
        product.setUpdate_time(resultSet.getString("update_time"));
        return product;
    }
}